# -*- coding: utf-8 -*-
"""
Created on Thu Aug 29 10:27:59 2019

@author: zhangjuefei
"""
import os
import json
import time, datetime 
import numpy as np
import pandas as pd

ROOT = "D:/documents/360_work/拍击手机"

data_dir = "dataprocess/data_v2"

os.chdir(os.path.join(ROOT, data_dir))

events = [
            "accelerometerEvent",
            "geomagneticEvent",
            "gravityEvent",
            "gyroscopeEvent",
            "linearOrientationEvent",
            "orientationEvent",
        ]

seq_len = 30

data = []
for file in os.listdir("."):
    if file == "log.txt":
        continue
    
    print(file)
    label = 0 if file.split(".")[0].split("_")[1] == "safe" else 1
    print(label)
    with open(file, "r", encoding="utf8") as f:
        
        values = []
        l = f.readline().strip()
        c = 0
        while l:
            
            j = json.loads(l)
            ok = True
            
            # timeArray = time.localtime(j["aapproxTime"] // 1000)
            # timestr = time.strftime("%Y--%m--%d %H:%M:%S", timeArray)
            # print(timestr)
            
            e_values = []
            for e in events:
                if e not in j:
                    ok = False
                    break
                
                e_values.extend(j[e]["values"])
            
            if ok:
                values.append(e_values)
            
            l = f.readline().strip()
            c += 1
        
        print(c)
        values = np.array(values).T

        for i in np.arange(0, values.shape[1] - seq_len, 30):
        # for i in range(values.shape[1] // seq_len):
            tmp = []
            # seq = values[:, i * seq_len:(i + 1) * seq_len]
            seq = values[:, i : i + seq_len]
            tmp.extend(seq.ravel())
            tmp.append(label)
            data.append(tmp)

data = pd.DataFrame(data)
print(data.shape)

data.to_csv(os.path.join(ROOT, "data.csv"), header=None, index=False)
            
            

